<template>
	<view class="calendar-section">
		<!-- 日历标题 -->
		<view class="calendar-title">
			<view class="calendar-icon">📅</view>
			<text class="calendar-name">默认日历</text>
			<view class="view-switch">视图</view>
		</view>
		
		<!-- 星期栏 -->
		<view class="weekday-row">
			<text 
				v-for="(day, index) in weekDays" 
				:key="index" 
				class="weekday"
			>{{ day }}</text>
		</view>
		
		<!-- 日期网格 -->
		<view 
			class="date-grid" 
			:class="{ 'collapsed': !calendarExpanded }"
			@touchstart="handleTouchStart"
			@touchend="handleTouchEnd"
		>
			<view 
				v-for="(date, index) in calendarDates" 
				:key="index"
				class="date-cell"
				:class="{ 
					'current-month': date.currentMonth, 
					'selected': date.selected,
					'today': date.today,
					'hidden': !calendarExpanded && !isDateInCurrentWeek(date, index)
				}"
				@click="selectDate(date)"
			>
				<text class="date-number">{{ date.day }}</text>
			</view>
		</view>
		
		<!-- 展开收起控制 -->
		<view class="calendar-toggle" @click="toggleCalendar">
			<view class="toggle-icon" :class="{ 'expanded': calendarExpanded }"></view>
		</view>

		<!-- 当前日期全信息 (合并自date-info组件) -->
		<view class="current-date-info">
			<text class="full-date">{{ fullDateInfo }}</text>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';

// 组件属性
const props = defineProps({
	selectedDate: {
		type: Date,
		default: () => new Date()
	}
});

// 组件事件
const emit = defineEmits(['dateSelected']);

// 星期几
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 日历是否展开
const calendarExpanded = ref(false);
// 触摸起始位置
const touchStartX = ref(0);
// 当前周偏移量
const currentWeekOffset = ref(0);

// 日历数据
const calendarDates = reactive([]);

// 当前内部日期（与父组件同步）
const currentDate = ref(new Date(props.selectedDate));

// 监听父组件日期变化
watch(() => props.selectedDate, (newDate) => {
	currentDate.value = new Date(newDate);
	generateCalendar();
});

// 生成日历数据
const generateCalendar = () => {
	const today = new Date();
	const current = new Date(currentDate.value);
	
	// 设置为当月第一天
	current.setDate(1);
	
	// 获取当月天数
	const daysInMonth = new Date(current.getFullYear(), current.getMonth() + 1, 0).getDate();
	
	// 获取当月第一天是星期几
	const firstDayOfWeek = current.getDay();
	
	// 清空日历数据
	calendarDates.length = 0;
	
	// 上个月的日期
	const lastMonth = new Date(current);
	lastMonth.setMonth(lastMonth.getMonth() - 1);
	const daysInLastMonth = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0).getDate();
	
	// 添加上个月的日期
	for (let i = firstDayOfWeek - 1; i >= 0; i--) {
		calendarDates.push({
			day: daysInLastMonth - i,
			currentMonth: false,
			selected: false,
			today: false,
			date: new Date(lastMonth.getFullYear(), lastMonth.getMonth(), daysInLastMonth - i)
		});
	}
	
	// 添加当月日期
	for (let i = 1; i <= daysInMonth; i++) {
		const isSelected = current.getFullYear() === currentDate.value.getFullYear() && 
						current.getMonth() === currentDate.value.getMonth() && 
						i === currentDate.value.getDate();
		
		calendarDates.push({
			day: i,
			currentMonth: true,
			selected: isSelected,
			today: current.getFullYear() === today.getFullYear() && 
				current.getMonth() === today.getMonth() && 
				i === today.getDate(),
			date: new Date(current.getFullYear(), current.getMonth(), i)
		});
	}
	
	// 添加下个月的日期
	const cellsNeeded = calendarExpanded.value ? 35 : 35; // 改为5行，即5*7=35个单元格
	const remainingCells = cellsNeeded - calendarDates.length;
	
	if (remainingCells > 0) {
		const nextMonth = new Date(current);
		nextMonth.setMonth(nextMonth.getMonth() + 1);
		
		for (let i = 1; i <= remainingCells; i++) {
			calendarDates.push({
				day: i,
				currentMonth: false,
				selected: false,
				today: false,
				date: new Date(nextMonth.getFullYear(), nextMonth.getMonth(), i)
			});
		}
	}
};

// 判断日期是否在当前周
const isDateInCurrentWeek = (date, index) => {
	if (calendarExpanded.value) return true;
	
	// 获取选中日期所在的周
	const currentDateObj = new Date(currentDate.value);
	const currentYear = currentDateObj.getFullYear();
	const currentMonth = currentDateObj.getMonth();
	const currentDay = currentDateObj.getDate();
	
	// 查找选中日期在日历中的索引
	let selectedIndex = -1;
	for (let i = 0; i < calendarDates.length; i++) {
		const d = calendarDates[i];
		if (d.currentMonth && d.day === currentDay) {
			selectedIndex = i;
			break;
		}
	}
	
	if (selectedIndex === -1) return false;
	
	// 计算选中日期所在的周
	const selectedWeek = Math.floor(selectedIndex / 7);
	
	// 当前显示的周 = 选中日期所在周 + 偏移量
	const displayWeek = (selectedWeek + currentWeekOffset.value) % 5;
	// 确保displayWeek为正数
	const normalizedDisplayWeek = displayWeek < 0 ? displayWeek + 5 : displayWeek;
	
	// 判断日期是否在当前显示的周
	return Math.floor(index / 7) === normalizedDisplayWeek;
};

// 选择日期
const selectDate = (date) => {
	if (!date.currentMonth) {
		// 如果选择的是上个月或下个月的日期，则切换到对应的月份
		const newDate = new Date(date.date);
		currentDate.value = newDate;
	} else {
		// 选择当月日期
		calendarDates.forEach(d => d.selected = false);
		date.selected = true;
		
		const newDate = new Date(currentDate.value);
		newDate.setDate(date.day);
		currentDate.value = newDate;
	}
	
	// 重置周偏移
	currentWeekOffset.value = 0;
	
	// 重新生成日历
	generateCalendar();
	
	// 向父组件通知日期变更
	emit('dateSelected', currentDate.value);
};

// 处理触摸开始
const handleTouchStart = (event) => {
	if (calendarExpanded.value) return;
	touchStartX.value = event.touches[0].clientX;
};

// 处理触摸结束
const handleTouchEnd = (event) => {
	if (calendarExpanded.value) return;
	
	const touchEndX = event.changedTouches[0].clientX;
	const diffX = touchEndX - touchStartX.value;
	
	// 判断是否为有效的滑动
	if (Math.abs(diffX) > 50) {
		if (diffX > 0) {
			// 向右滑动，显示上一周
			changeWeek(-1);
		} else {
			// 向左滑动，显示下一周
			changeWeek(1);
		}
	}
};

// 切换周
const changeWeek = (offset) => {
	// 仅更新周偏移，不改变选中日期
	currentWeekOffset.value += offset;
	
	// 重新生成日历，但不更新currentDate
	const tempDate = new Date(currentDate.value);
	generateCalendar();
};

// 切换日历展开/折叠
const toggleCalendar = () => {
	calendarExpanded.value = !calendarExpanded.value;
	
	// 折叠时重置周偏移
	if (!calendarExpanded.value) {
		currentWeekOffset.value = 0;
	}
	
	// 重新生成日历
	generateCalendar();
};

// 格式化当前日期（月日+简约视图）
const formattedCurrentDate = computed(() => {
	const month = currentDate.value.getMonth() + 1;
	const day = currentDate.value.getDate();
	return `${month}月${day}日·简约视图`;
});

// 日期全信息 (从date-info组件合并过来)
const fullDateInfo = computed(() => {
	const year = currentDate.value.getFullYear();
	const month = (currentDate.value.getMonth() + 1).toString().padStart(2, '0');
	const day = currentDate.value.getDate().toString().padStart(2, '0');
	const weekDay = weekDays[currentDate.value.getDay()];
	return `${year}-${month}-${day} 周${weekDay}`;
});

// 对外暴露的方法
defineExpose({
	formattedCurrentDate,
	generateCalendar,
	fullDateInfo
});

// 初始化
generateCalendar();
</script>

<style lang="scss" scoped>
.calendar-section {
	padding: 10rpx 20rpx;
	// border-bottom: 1rpx solid #f0f0f0; // 移除整个组件的底部边框
	flex-shrink: 0;
	position: relative;
	max-height: 480rpx;
	
	// 日历标题
	.calendar-title {
		display: flex;
		align-items: center;
		margin-bottom: 6rpx;
		height: 60rpx;
		
		.calendar-icon {
			font-size: 32rpx;
			margin-right: 6rpx;
			color: #0066FF;
		}
		
		.calendar-name {
			font-size: 28rpx;
			font-weight: bold;
			flex: 1;
		}
		
		.view-switch {
			font-size: 22rpx;
			color: #999;
			padding: 6rpx 12rpx;
			border: 1rpx solid #eee;
			border-radius: 24rpx;
		}
	}
	
	.weekday-row {
		display: flex;
		justify-content: space-around;
		padding: 6rpx 0;
		height: 40rpx;
		
		.weekday {
			width: 14.28%;
			text-align: center;
			font-size: 22rpx;
			color: #999;
		}
	}
	
	.date-grid {
		display: flex;
		flex-wrap: wrap;
		transition: all 0.3s ease;
		overflow: hidden;
		max-height: 350rpx;
		border-bottom: 1rpx solid #f0f0f0;
		padding-bottom: 8rpx;
		
		&.collapsed {
			max-height: 60rpx;
			overflow-x: auto;
			overflow-y: hidden;
			flex-wrap: nowrap;
			-webkit-overflow-scrolling: touch;
			position: relative;
			scroll-behavior: smooth;
			
			.date-cell {
				flex-shrink: 0;
				
				&.selected {
					border-radius: 6rpx;
					position: relative;
					
					&:after {
						content: '';
						position: absolute;
						bottom: 4rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 6rpx;
						height: 6rpx;
						border-radius: 50%;
						background-color: #FFFFFF;
					}
				}
			}
			
			&:before {
				content: "← 滑动 →";
				position: absolute;
				right: 10rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 20rpx;
				color: #999;
				padding: 3rpx 6rpx;
				border-radius: 8rpx;
				background-color: rgba(255, 255, 255, 0.8);
				animation: fadeOut 2s forwards 1s;
				z-index: 10;
			}
			
			&:after {
				content: '';
				position: absolute;
				right: 0;
				top: 0;
				height: 100%;
				width: 30rpx;
				background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,1));
				pointer-events: none;
			}
		}
		
		@keyframes fadeOut {
			from { opacity: 1; }
			to { opacity: 0; }
		}
		
		.date-cell {
			width: 14.28%;
			height: 58rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			
			.date-number {
				font-size: 24rpx;
				color: #999;
			}
			
			&.current-month {
				.date-number {
					color: #333;
				}
			}
			
			&.today {
				.date-number {
					color: #0066FF;
				}
			}
			
			&.selected {
				background-color: #0066FF;
				border-radius: 6rpx;
				
				.date-number {
					color: #ffffff;
				}
			}
			
			&.hidden {
				display: none;
			}
		}
	}
	
	.calendar-toggle {
		display: flex;
		justify-content: center;
		padding: 8rpx 0 0;
		cursor: pointer;
		height: 30rpx;
		
		.toggle-icon {
			width: 22rpx;
			height: 22rpx;
			border-top: 2rpx solid #999;
			border-right: 2rpx solid #999;
			transform: rotate(135deg);
			transition: transform 0.3s ease;
			
			&.expanded {
				transform: rotate(-45deg);
			}
		}
	}

	// 当前日期信息 (从date-info组件合并过来)
	.current-date-info {
		padding: 12rpx 10rpx;
		flex-shrink: 0;
		border-bottom: 1rpx solid #f0f0f0;
		
		.full-date {
			font-size: 28rpx;
			font-weight: bold;
		}
	}
}
</style> 